package com.donghua.controller;

import com.donghua.entity.DiscussPost;
import com.donghua.entity.LoginTicket;
import com.donghua.entity.Picture;
import com.donghua.entity.User;
import com.donghua.service.DiscussPostService;
import com.donghua.service.LikeService;
import com.donghua.service.UserService;
import com.donghua.util.CookieUtil;
import com.donghua.util.HostHolder;
import com.donghua.util.RedisKeyUtil;
import com.donghua.util.Result;
import com.donghua.vo.PostListVO;
import com.donghua.vo.PostListVOPlus;
import com.donghua.vo.UserDetailInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import static com.donghua.enums.StatusCodeEnum.SUCCESS;
import static com.donghua.util.CommunityConstant.ENTITY_TYPE_POST;

@Controller
public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(path = "/postlist", method = RequestMethod.GET)
    @ResponseBody
    public Result<?> getIndexPage(@RequestParam(name = "userId", defaultValue = "0") int userId, Integer offset, Integer limit, HttpServletRequest request) {

        List<DiscussPost> list = discussPostService.findDiscussPosts(userId, offset, limit);
        Map<String, Object> data = new HashMap<>();
        List<Map<String, Object>> postList = new ArrayList<>();
        if (list != null) {
            for (DiscussPost post : list) {
                Map<String, Object> map = new HashMap<>();
                PostListVOPlus postListVO = new PostListVOPlus();
                //插入每个tag对应的id
                List<Integer> tagIds = new ArrayList<>();
                List<String> tagNames = discussPostService.getDiscussPostTags(post.getId());
                for(String tagName : tagNames) {
                    tagIds.add(discussPostService.findTagIdByTagName(tagName));
                }
                List<Map<String, Object>> tags = new ArrayList<>();
                for(int i = 0; i < tagNames.size(); i++) {
                    Map<String, Object> tag = new HashMap<>();
                    tag.put("tagId", tagIds.get(i));
                    tag.put("tagName", tagNames.get(i));
                    tags.add(tag);
                }
                postListVO.setTags(tags);
                postListVO.setCreateTime(post.getCreateTime());
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                postListVO.setLikeCount((int) likeCount);
                postListVO.setCommentCount(post.getCommentCount());
                postListVO.setId(post.getId());
                postListVO.setTitle(post.getTitle());
                postListVO.setContent(post.getContent());
                // 从cookie中获取凭证
                String ticket = CookieUtil.getValue(request, "ticket");
                boolean flag = false;
                if (ticket != null) {
                    // 查询凭证
                    String redisKey = RedisKeyUtil.getTicketKey(ticket);
                    LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
                    // 检查凭证是否有效
                    if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                        // 根据凭证查询用户
                        User user = userService.findUserById(loginTicket.getUserId());
                        hostHolder.setUser(user);
                        flag = true;
                    }
                }
                // 点赞状态
                int likeStatus = !flag ? 0 :
                        likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_POST, postListVO.getId());
                postListVO.setLikeStatus(likeStatus);
                // 帖子对应的图片
                List<Picture> pics = discussPostService.findPicturesByPostId(post.getId());
                List<String> picUrls = new ArrayList<>();
                for(int i = 0; i < pics.size(); i++) {
                    picUrls.add(pics.get(i).getPictureUrl());
                }
                postListVO.setPictureUrls(picUrls);
                map.put("post", postListVO);
                //user
                User user = userService.findUserById(post.getUserId());
                UserDetailInfo userDetailInfo = new UserDetailInfo();
                userDetailInfo.setId(user.getId());
                userDetailInfo.setNickName(user.getNickName());
                userDetailInfo.setDescription(user.getDescription());
                userDetailInfo.setUsername(user.getUsername());
                userDetailInfo.setType(user.getType());
                userDetailInfo.setStatus(user.getStatus());
                userDetailInfo.setCreateTime(user.getCreateTime());
                userDetailInfo.setHeaderUrl(user.getHeaderUrl());
                userDetailInfo.setBackgroundUrl(user.getBackgroundUrl());
                map.put("user", userDetailInfo);
                postList.add(map);
            }
        }
        data.put("postList", postList);
        //帖子总数
        int postCount = discussPostService.findDiscussPostRows(userId);
        data.put("postCount", postCount);

        logger.info("帖子列表查询成功");
        return Result.ok(SUCCESS.getCode(), SUCCESS.getMsg(), data);
    }

    @RequestMapping(path = "/hotTag", method = RequestMethod.GET)
    @ResponseBody
    public Result<?> getHotTag(int offset, int limit) {
        List<Integer> list = discussPostService.findHotTagId(offset, limit);
        List<Map<String, Object>> data = new ArrayList<>();
        for(int i = 0; i < list.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("tagId", list.get(i));
            map.put("tagName", discussPostService.findTagById(list.get(i)).getTagName());
            data.add(map);
        }
        logger.info("热标签列表查询成功");
        return Result.ok(SUCCESS.getCode(), SUCCESS.getMsg(), data);
    }

    @RequestMapping(path = "hotPost", method = RequestMethod.GET)
    @ResponseBody
    public Result<?> getHotPost(int tagId, int offset, int limit, HttpServletRequest request) {
        List<Integer> postIdList = discussPostService.findPostIdByTagId(tagId, offset, limit);
        List<DiscussPost> list = new ArrayList<>();
        for(int i = 0; i < postIdList.size(); i++) {
            DiscussPost discussPost= discussPostService.findDiscussPostById(postIdList.get(i));
            list.add(discussPost);
        }   
        Map<String, Object> data = new HashMap<>();
        List<Map<String, Object>> postList = new ArrayList<>();
        if (list != null) {
            for (DiscussPost post : list) {
                Map<String, Object> map = new HashMap<>();

                PostListVOPlus postListVO = new PostListVOPlus();
                //插入每个tag对应的id
                List<Integer> tagIds = new ArrayList<>();
                List<String> tagNames = discussPostService.getDiscussPostTags(post.getId());
                for(String tagName : tagNames) {
                    tagIds.add(discussPostService.findTagIdByTagName(tagName));
                }
                List<Map<String, Object>> tags = new ArrayList<>();
                for(int i = 0; i < tagNames.size(); i++) {
                    Map<String, Object> tag = new HashMap<>();
                    tag.put("tagId", tagIds.get(i));
                    tag.put("tagName", tagNames.get(i));
                    tags.add(tag);
                }
                postListVO.setTags(tags);
                postListVO.setCreateTime(post.getCreateTime());
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                postListVO.setLikeCount((int) likeCount);
                postListVO.setCommentCount(post.getCommentCount());
                postListVO.setId(post.getId());
                postListVO.setTitle(post.getTitle());
                postListVO.setContent(post.getContent());
                // 从cookie中获取凭证
                String ticket = CookieUtil.getValue(request, "ticket");
                boolean flag = false;
                if (ticket != null) {
                    // 查询凭证
                    String redisKey = RedisKeyUtil.getTicketKey(ticket);
                    LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
                    // 检查凭证是否有效
                    if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                        // 根据凭证查询用户
                        User user = userService.findUserById(loginTicket.getUserId());
                        hostHolder.setUser(user);
                        flag = true;
                    }
                }
                // 点赞状态
                int likeStatus = !flag ? 0 :
                        likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_POST, postListVO.getId());
                postListVO.setLikeStatus(likeStatus);
                // 帖子对应的图片
                List<Picture> pics = discussPostService.findPicturesByPostId(post.getId());
                List<String> picUrls = new ArrayList<>();
                for(int i = 0; i < pics.size(); i++) {
                    picUrls.add(pics.get(i).getPictureUrl());
                }
                postListVO.setPictureUrls(picUrls);
                map.put("post", postListVO);
                User user = userService.findUserById(post.getUserId());
                UserDetailInfo userDetailInfo = new UserDetailInfo();
                userDetailInfo.setId(user.getId());
                userDetailInfo.setNickName(user.getNickName());
                userDetailInfo.setDescription(user.getDescription());
                userDetailInfo.setUsername(user.getUsername());
                userDetailInfo.setType(user.getType());
                userDetailInfo.setStatus(user.getStatus());
                userDetailInfo.setCreateTime(user.getCreateTime());
                userDetailInfo.setHeaderUrl(user.getHeaderUrl());
                userDetailInfo.setBackgroundUrl(user.getBackgroundUrl());
                map.put("user", userDetailInfo);
                postList.add(map);
            }
        }
        String tagName = discussPostService.findTagById(tagId).getTagName();
        data.put("postList", postList);
        data.put("tagName", tagName);
        logger.info("热帖列表查询成功");
        return Result.ok(SUCCESS.getCode(), SUCCESS.getMsg(), data);

    }
}